<?php
// ini_set('display_errors', 'on');
class OauthApp extends MallbaseApp {
	function index() {
		import('WxPayPubHelper/WxPay.pub.config');
		if (!isset($_GET['code'])) {
			$retUrl = urlencode("http://m.zimaozhigou.com/mobile/index.php?app=oauth");
			$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . WxPayConf_pub::APPID . "&redirect_uri=" . $retUrl . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
			header("Location:$url");
		} else {
			header("Content-type: text/html; charset=utf-8");
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . WxPayConf_pub::APPID . "&secret=" . WxPayConf_pub::APPSECRET . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
			$data = $this -> _curl($url);
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $data['access_token'] . "&openid=" . $data['openid'] . "&lang=zh_CN";
			$userinfo = $this -> _curl($url);
			$_SESSION['openid'] = $userinfo['openid'];
			//检查该微信用户是否注册，没注册完成注册流程，已注册的话完成登录流程。
			/* 注册并登陆 */
			$ms = &ms();
				//连接用户中心
			if($ms->user->check_openid($userinfo['openid'])){
				$code = new Code();
				$card_no = $code -> encodeID(rand(1,999999), 5);
				$card_pre = '022';
				$card_vc = substr(md5($card_pre . $card_no), 0, 2);
				$card_vc = strtoupper($card_vc);
				$user_name = $card_pre . $card_no . $card_vc;
				//$user_name = trim($userinfo['user_name']);
				//echo $user_name;
				$password = $user_name;
				$email = $user_name."@zimaozhigou.com";
				$passlen = strlen($password);
				$user_name_len = strlen($user_name);
				$portrait = $userinfo['headimgurl'];
				//$phone_mob = trim($_POST['phone_mob']);
				//$code = trim($_POST['code']);
	
			
				
				if (!$ms -> user -> check_username($user_name)) {
					$card_no = $code -> encodeID(rand(1,999999), 5);
					$card_pre = '022';
					$card_vc = substr(md5($card_pre . $card_no), 0, 2);
					$card_vc = strtoupper($card_vc);
					$user_name = $card_pre . $card_no . $card_vc;
					//$user_name = trim($userinfo['user_name']);
					//echo $user_name;
					$password = $user_name;
					$email = $user_name."@zimaozhigou.com";
					$passlen = strlen($password);
					$user_name_len = strlen($user_name);
				}
	
				if ($user_name_len < 3 || $user_name_len > 25) {
					$this -> json_error('user_name_length_error');
	
					return;
				}
				if ($passlen < 6 || $passlen > 20) {
					$this -> json_error('password_length_error');
	
					return;
				}
				if (!is_email($email)) {
					$this -> json_error('email_error');
					return;
				}
				
				$user_id = $ms -> user -> register($user_name, $password, $email,array("openid"=>$userinfo['openid'],"real_name"=>$userinfo['nickname'],"nickname"=>$userinfo['nickname'],"portrait"=>$portrait));
	
				if (!$user_id) {
					$this -> json_error($ms -> user -> get_error());
	
					return;
				}
				$this -> _hook('after_register', array('user_id' => $user_id));
				//登录
				$this -> _do_login($user_id);
	
				/* 同步登陆外部系统 */
				$synlogin = $ms -> user -> synlogin($user_id);
				//var_dump($_SESSION);
				#TODO 可能还会发送欢迎邮件
				//$this -> json_result('', 'register_success');
			} else {
				//echo "Login as ".$userinfo['openid'];
				$model_user =& m('member');
            	$user = $model_user->get("openid='".$userinfo['openid']."'");
				$this -> _do_login($user['user_id']);
	
				/* 同步登陆外部系统 */
				$synlogin = $ms -> user -> synlogin($user['user_id']);
				//var_dump($_SESSION);
			}
			//获取返回URL
			$ret_url = $_SESSION['ret_url'];
			if($ret_url == ''){
				$ret_url = '/mobile/index.php?app=member';
			}
			unset($_SESSION['ret_url']);
			header("Location:$ret_url");

		}

	}

	function o() {
		$this->logout();
	}
	
	function _curl($url) {
		//$url = $this -> createOauthUrlForOpenid();
		// 初始化curl
		$ch = curl_init();
		//$curl_timeout =  $this->curl_timeout;
		//设置超时
		// $this_header = array(
		// "content-type: application/x-www-form-urlencoded;
		// charset=UTF-8"
		// );
		//curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//运行curl，结果以jason形式返回
		$res = curl_exec($ch);
		curl_close($ch);
		//取出openid
		$data = json_decode($res, true);

		//$this -> openid = $data['openid'];
		//$this->access_token = $data['access_token'];
		//var_dump($data);
		return $data;
	}

}

class Code {
	//密码字典
	private $dic = array(0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => 'A', 11 => 'B', 12 => 'C', 13 => 'D', 14 => 'E', 15 => 'F', 16 => 'G', 17 => 'H', 18 => 'I', 19 => 'J', 20 => 'K', 21 => 'L', 22 => 'M', 23 => 'N', 24 => 'O', 25 => 'P', 26 => 'Q', 27 => 'R', 28 => 'S', 29 => 'T', 30 => 'U', 31 => 'V', 32 => 'W', 33 => 'X', 34 => 'Y', 35 => 'Z');

	public function encodeID($int, $format = 8) {
		$dics = $this -> dic;
		$dnum = 36;
		//进制数
		$arr = array();
		$loop = true;
		while ($loop) {
			$arr[] = $dics[bcmod($int, $dnum)];
			$int = bcdiv($int, $dnum, 0);
			if ($int == '0') {
				$loop = false;
			}
		}
		if (count($arr) < $format)
			$arr = array_pad($arr, $format, $dics[0]);

		return implode('', array_reverse($arr));
	}

	public function decodeID($ids) {
		$dics = $this -> dic;
		$dnum = 36;
		//进制数
		//键值交换
		$dedic = array_flip($dics);
		//去零
		$id = ltrim($ids, $dics[0]);
		//反转
		$id = strrev($id);
		$v = 0;
		for ($i = 0, $j = strlen($id); $i < $j; $i++) {
			$v = bcadd(bcmul($dedic[$id{$i}], bcpow($dnum, $i, 0), 0), $v, 0);
		}
		return $v;
	}

}
?>
